package com.awccis.admin.controller;

import com.awccis.admin.model.merchant.CombineMerchantBean;
import com.awccis.admin.model.merchant.MerchantBean;
import com.awccis.admin.model.pay.MerchantPaDetailInfo;
import com.awccis.admin.model.sorder.CombineServiceBean;
import com.awccis.admin.model.sorder.CombineTypeBean;
import com.awccis.admin.model.sorder.ServiceOrderBean;
import com.awccis.admin.model.sorder.ServiceTypeBean;
import com.awccis.admin.service.AdminServiceOrderService;
import com.awccis.common.utils.Constants;
import com.awccis.common.utils.JsonUtil;
import com.awccis.common.utils.SendMailToAdmin;
import com.awccis.common.utils.SendMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.util.*;

/**
 * @author: txp
 * @date: 2018/5/30 on 下午3:37
 * @since: 1.0
 * @description:
 */
@Controller
@RequestMapping("/serviceOrder")
public class AdminServiceOrderController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(AdminServiceOrderController.class);

    @Resource
    private AdminServiceOrderService adminServiceOrderService;


    /**
     * 添加新的商户信息
     *
     * @param combineMerchantBean {"type": "insert", "merchant": {"merchantId": 1, .....}}
     * @return {}
     */
    @RequestMapping(value = "/operateMerchant", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> operateMerchant(@RequestBody CombineMerchantBean combineMerchantBean) {
        logger.info("添加新的商户信息：" + combineMerchantBean.toString());

        Map<String, Object> map = new HashMap<>();

        if (combineMerchantBean.getType() != null && !combineMerchantBean.getType().equals("")
                && combineMerchantBean.getMerchantBean() != null) {
            MerchantBean merchantBean = combineMerchantBean.getMerchantBean();
            switch (combineMerchantBean.getType()) {
                case "insert":
                    boolean result1 = adminServiceOrderService.setMerchantInfo("insert", merchantBean);
                    map.put(Constants.MAP_KEY_RESULT, result1);
                    if (result1) {
                        map.put(Constants.MAP_KEY_MESSAGE, "注册成功！");
                    } else {
                        map.put(Constants.MAP_KEY_MESSAGE, "注册失败！");
                    }
                    break;
                case "update":
                    boolean result2 = adminServiceOrderService.setMerchantInfo("update", merchantBean);
                    map.put(Constants.MAP_KEY_RESULT, result2);
                    if (result2) {
                        map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
                    } else {
                        map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
                    }
                    break;
                case "delete":
                    boolean result3 = adminServiceOrderService.setMerchantInfo("delete", merchantBean);
                    map.put(Constants.MAP_KEY_RESULT, result3);
                    if (result3) {
                        map.put(Constants.MAP_KEY_MESSAGE, "删除成功！");
                    } else {
                        map.put(Constants.MAP_KEY_MESSAGE, "删除失败！");
                    }
                    break;
                default:
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "操作类型非法！");
                    break;
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数出错！");
        }

        return map;
    }

    /**
     * 查询不同的商户
     *
     * @param hashMap {"type":"all", "merchantId": "2"}
     * @return
     */
    @RequestMapping(value = "/queryMerchant", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> queryMerchant(@RequestBody HashMap<String, String> hashMap) {
        logger.info("查询商户信息：" + hashMap);

        Map<String, Object> map = new HashMap<>();

        String type = "type";
        String id = "merchantId";
        if (hashMap.get(type) != null) {
            switch (hashMap.get(type)) {
                case "id":
                    MerchantBean merchantBean = null;
                    try {
                        merchantBean = adminServiceOrderService.getMerchantInfoById(Integer.parseInt(hashMap.get(id)));
                    } catch (NumberFormatException e) {
                        logger.warn("根据ID获取商户信息非法请求：" + e + "::::" + hashMap.get(id));
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法！");
                        return map;
                    }
                    if (merchantBean != null) {
                        map.put(Constants.MAP_KEY_RESULT, true);
                        map.put(Constants.MAP_KEY_MESSAGE, merchantBean);
                    } else {
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "商户不存在！");
                    }
                    break;
                default:
                    List<MerchantBean> list = adminServiceOrderService.selectMerchantInfoByType(hashMap.get(type));
                    if (list.size() > 0) {
                        map.put(Constants.MAP_KEY_RESULT, true);
                        map.put(Constants.MAP_KEY_MESSAGE, list);
                    } else {
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "当前没有" + hashMap.get(type) + "类型的商户！");
                    }
                    break;
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法!");
        }

        return map;
    }

    /**
     * 查看所有预约订单
     *
     * @param hashMap {"AWCCIS_CODE": "1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return map
     */
    @RequestMapping(value = "/reservationList", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map reservationList(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取预约订单信息：" + hashMap);
        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) != null && Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))) {
            List<ServiceOrderBean> list = adminServiceOrderService.getAllServiceOrder();
            if (list.size() == 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "当前还没有预约订单！");
            } else {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }

        return map;
    }

    /**
     * 添加一条新的预约订单
     *
     * @param combineServiceBean {
     *                           "setType":"insert",
     *                           "serviceOrderBean":
     *                           {
     *                           "serviceOrderId":1,
     *                           "serviceId":2,
     *                           "customerId":30,
     *                           "customerName":"tw",
     *                           "serviceOrderStartTime":"2018-06-05",
     *                           "serviceOrderEndTime":"2018-06-95",
     *                           "serviceOrderInfo":"请求园艺服务，这是。。。。。。。。。",
     *                           "serviceOrderMoney":11.2,
     *                           "serviceOrderPhone":"+8612345678912",
     *                           "serviceOrderOperator":"txp",
     *                           "serviceOrderOperatorTime":"2018-06-06"
     *                           }
     *                           }
     *                           <p>
     *                           {
     *                           "setType":"update",
     *                           "serviceOrderBean":
     *                           {
     *                           "serviceOrderId":1,
     *                           "serviceOrderMoney":11.2,
     *                           "serviceOrderOperator":"txp",
     *                           "serviceOrderOperatorTime":"2018-06-06"
     *                           }
     *                           }
     *                           <p>
     *                           {
     *                           "setType":"delete",
     *                           "serviceOrderBean":
     *                           {
     *                           "serviceOrderId":1,
     *                           }
     *                           }
     * @return map
     */
    @RequestMapping(value = "/setServiceOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map setServiceOrder(@RequestBody CombineServiceBean combineServiceBean) {
        logger.info("增加新的预约订单：" + combineServiceBean.toString());
        Map map = new HashMap(2);

        switch (combineServiceBean.getSetType()) {
            case "insert":
                ServiceOrderBean serviceOrderBean = combineServiceBean.getServiceOrderBean();
                boolean result = adminServiceOrderService.setNewServiceOrder(serviceOrderBean);
                if (result) {
                    try {
                        SendMailToAdmin.sendTextEmail(JsonUtil.getJsonConfigValue("adminEmail"), "有新的预约订单", "管理员用户您好，您有新的预约订单待处理，请登录管理平台尽快处理！\n" + "\n"
                                + "\n" + "\n" + "预约订单人联系方式：" + serviceOrderBean.getServiceOrderPhone()
                                + "\n" + "\n" + "预约订单内容：" + serviceOrderBean.getServiceOrderInfo()
                                + "\n" + "\n" + "预约订单时间：" + serviceOrderBean.getServiceOrderStartTime()
                                + "\n" + "\n" + "预约订单预计结束时间：" + serviceOrderBean.getServiceOrderEndTime()
                                + "\n" + "\n" + "祝您生活愉快！",false,null);
                    } catch (Exception e) {
                        logger.warn("预约订单向");
                    }
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "添加成功！");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "添加失败！");
                }
                break;
            case "update":
                ServiceOrderBean serviceOrderBean1 = combineServiceBean.getServiceOrderBean();
                if(serviceOrderBean1.getMerchantId() <= 0){
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "商户请求值非法");
                    return map;
                }
                boolean result1 = adminServiceOrderService.updateServiceOrder(serviceOrderBean1);
                if (result1) {
                    //在预约订单确认完成
                    String headMsg = "【AWCCIS】 \n E加家 平台信息\n";
                    String statusMsg = "预约状态：已受理 \n";
                    String startTimeMsg = "预约时间：" + serviceOrderBean1.getServiceOrderStartTime() + "\n";
                    String endTimeMsg = "预约结束：" + serviceOrderBean1.getServiceOrderEndTime() + "\n";
                    String locationMsg = "预约地址：" + "\n";
                    String infoMsg = "预约信息：" + serviceOrderBean1.getServiceOrderInfo() + "\n";
                    String phoneCustomerMsg = "客户联系电话：" + serviceOrderBean1.getServiceOrderPhone();
                    String phoneDealMsg = "商户联系电话：" + serviceOrderBean1.getServiceOrderDealPhone();

                    String msgToCustomer = headMsg + statusMsg + startTimeMsg + infoMsg + phoneDealMsg;
                    String msgToMerchant = headMsg + startTimeMsg + endTimeMsg + infoMsg + phoneCustomerMsg;

                    String s1 = SendMessageUtil.sendMessageTo(serviceOrderBean1.getServiceOrderPhone(), msgToCustomer);
                    String s2 = SendMessageUtil.sendMessageTo(serviceOrderBean1.getServiceOrderDealPhone(), msgToMerchant);
                    System.out.println("给用户发送短信：" + s1 + "\n" + msgToCustomer);
                    System.out.println("给商户发送短信：" + s2 + "\n" + msgToMerchant);
                    logger.info("给用户发送短信" + s1);
                    logger.info("给商户发送短信" + s2);

                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "更改成功！ ");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "更改失败！ ");
                }
                break;
            case "updateStatus":
                int id = combineServiceBean.getServiceOrderBean().getServiceOrderId();
                String status = combineServiceBean.getServiceOrderBean().getStatusId() + "";
                boolean updateResult = adminServiceOrderService.updateServiceStatus(id, status);
                map.put(Constants.MAP_KEY_RESULT, updateResult);
                if (updateResult) {
                    map.put(Constants.MAP_KEY_MESSAGE, "更改成功!");
                } else {
                    map.put(Constants.MAP_KEY_MESSAGE, "状态值非法！");
                }
                break;
            case "delete":
                ServiceOrderBean serviceOrderBean2 = combineServiceBean.getServiceOrderBean();
                boolean result2 = adminServiceOrderService.deleteServiceOrder(serviceOrderBean2.getServiceOrderId());
                if (result2) {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "删除成功！");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "删除失败！");
                }
                break;
            case "select":
                ServiceOrderBean serviceOrderBean3 = combineServiceBean.getServiceOrderBean();
                int statusId = serviceOrderBean3.getStatusId();
                int orderId = serviceOrderBean3.getServiceOrderId();
                ServiceOrderBean resultServiceOrderBean = adminServiceOrderService.getServiceOrderDetailInfo(statusId, orderId);
                if (resultServiceOrderBean != null) {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, resultServiceOrderBean);
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "预约订单不存在！");
                }
                break;
            default:
                break;
        }
        return map;
    }

    /**
     * 查询服务订单
     *
     * @param combineServiceBean {"statusId": 1, "setType":"一键保洁"} all
     * @return {}
     */
    @RequestMapping(value = "/queryServiceOrders", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> queryServiceOrders(@RequestBody CombineServiceBean combineServiceBean) {
        logger.info("查询服务订单：" + combineServiceBean.toString());

        Map<String, Object> map = new HashMap<>();
        if (combineServiceBean.getStatusId() != -2 && combineServiceBean.getSetType() != null && !"".equals(combineServiceBean.getSetType())) {
            List<ServiceOrderBean> list;

            switch (combineServiceBean.getSetType()) {
                case "all":
                    list = adminServiceOrderService.getAllServiceOrder();
                    break;
                default:
                    list = adminServiceOrderService.getDiffStatusAndTypeServiceOrder(combineServiceBean.getStatusId(), combineServiceBean.getSetType());
                    break;
            }
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "当前没有状态值为" + combineServiceBean.getStatusId() + "的" + combineServiceBean.getSetType() + "类型的订单！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法！");
        }

        return map;

    }

    /**
     * 获取所有service类型
     *
     * @param hashMap {"AWCCIS_CODE": "1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return map
     */
    @RequestMapping(value = "/getAllServiceType", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map getAllServiceType(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取service类型" + hashMap);
        Map map = new HashMap(2);

        String awccisCode = "AWCCIS_CODE";
        if (hashMap.get(awccisCode) != null && Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))) {
            List<ServiceTypeBean> list = adminServiceOrderService.getAllServiceType();
            if (list.size() == 0) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "当前还没有订单！");
            } else {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }
        return map;
    }


    /**
     * 更改service类型
     *
     * @param combineTypeBean {
     *                        "type":"insert",
     *                        "serviceTypeBean":
     *                        {
     *                        "serviceId":1,
     *                        "serviceName":"sss",
     *                        "servicePrice":11.2
     *                        }
     *                        }
     * @return map
     */
    @RequestMapping(value = "/setServiceType", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map setServiceType(@RequestBody CombineTypeBean combineTypeBean) {
        logger.info("更改service类型" + combineTypeBean.toString());

        Map map = new HashMap(2);

        switch (combineTypeBean.getType()) {
            case "insert":
                ServiceTypeBean serviceTypeBean = combineTypeBean.getServiceTypeBean();
                boolean result = adminServiceOrderService.setNewServiceType(serviceTypeBean);
                if (result) {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "添加成功！ ");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "添加失败！");
                }
                break;
            case "update":
                ServiceTypeBean serviceTypeBean1 = combineTypeBean.getServiceTypeBean();
                boolean result1 = adminServiceOrderService.updateServiceType(serviceTypeBean1);
                if (result1) {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "更改成功！ ");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
                }
                break;
            case "delete":
                ServiceTypeBean serviceTypeBean2 = combineTypeBean.getServiceTypeBean();
                boolean result2 = adminServiceOrderService.deleteServiceType(serviceTypeBean2.getServiceId());
                if (result2) {
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, "删除成功！ ");
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "删除失败！");
                }
                break;
            default:
                break;
        }
        return map;
    }

    /**
     * 获取本周需要缴费的司机
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {}
     */
    @RequestMapping(value = "/selectMerchantNeedPay", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> selectMerchantNeedPay(@RequestBody HashMap<String, String> hashMap) {
        logger.info("获取本周需要缴费的商户：" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        String awccisCode = hashMap.get("AWCCIS_CODE");
        if(awccisCode!=null){
            String type = hashMap.get("type");
            Calendar cl = Calendar.getInstance();
            int week = cl.get(Calendar.WEEK_OF_YEAR)-1;
            cl.add(Calendar.DAY_OF_MONTH, -7);
            int year = cl.get(Calendar.YEAR);
            if (week < cl.get(Calendar.WEEK_OF_YEAR)) {
                year += 1;
            }
            String payWeek = year + "年第" + week + "周";
            System.out.println(payWeek);
            switch (type){
                case "all":
                    break;
                case "week":
                    List<MerchantPaDetailInfo> list = adminServiceOrderService.getMerchantNeedPay("second", payWeek);
                    if(list.size()>0){
                        map.put(Constants.MAP_KEY_RESULT, true);
                        map.put(Constants.MAP_KEY_MESSAGE, list);
                    }else {
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "当前没有需要缴费的商户");
                    }
                    break;
                default:
                    break;
            }
        }
        return map;
    }

    /**
     * 更改商户已经缴费状态
     * @param hashMap {"mpayId": "12", "AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {}
     */
    @RequestMapping(value = "/setMerchantPayRecord", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map<String, Object> setMerchantPayRecord(@RequestBody HashMap<String, String> hashMap){
        logger.info("更改商户为已经缴费状态：" + hashMap);

        Map<String, Object> map = new HashMap<>();
        String awccisCode = "AWCCIS_CODE";
        String id = "mpayId";
        if(hashMap.get(awccisCode) != null && Constants.AWCCIS_CODE.equals(hashMap.get(awccisCode))
                && hashMap.get(id) != null && !"".equals(hashMap.get(id))){
            int mpayId;
            try {
                mpayId = Integer.parseInt(hashMap.get(id));
            } catch (NumberFormatException e) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求ID非法！");
                return map;
            }
            boolean result = adminServiceOrderService.setMerchantPayRecord(mpayId);
            map.put(Constants.MAP_KEY_RESULT, result);
            if(result){
                map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
            }else {
                map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法！");
        }

        return map;
    }
}
